//
//  AlbumVC.m
//  CarHome
//
//  Created by 蒋寒霄 on 14-9-23.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "AlbumVC.h"

//Model
#import "AblumModel.h"
//ThirdParty
#import "UIImageView+WebCache.h"



#import "AFNetworking.h"

@interface AlbumVC ()<UIScrollViewDelegate>
{
    UIScrollView *_scroll;//相册底层
    UIView *_up_View;//上部底层
    UIView *_down_View;//下部底层
    UILabel *_titleLabel;//显示张数
    
    //数据变量
    NSMutableArray *_ablumArray;//相册数据
    NSMutableArray *_ablumCategory;//相册目录
    int _imageID;
    int _image_SS;
    int _image_SP;
}
@end

@implementation AlbumVC

- (void)dealloc
{
    [_ablumArray release];
    _ablumArray = nil;
    [_ablumCategory release];
    _ablumCategory = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = [UIColor blackColor];
        _ablumArray = [[NSMutableArray alloc] init];
        _ablumCategory = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //创建视图
    [self createUpView];
    [self createScrollAblum];
    
}
#pragma mark -
#pragma mark 进行网络请求

// 最新网络请求
- (void)connectURL
{
    [NetUrl connect:[NSString stringWithFormat:AblumURL, _image_SS, _image_SP, _imageID] parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        AblumModel *ablum = [AblumModel returnAblumModel:dic];
        //第一个接口
        [_ablumArray addObjectsFromArray:ablum.ablum_list];
        [_ablumCategory addObjectsFromArray:ablum.ablum_categorys];
//        [self createDownView];
        for (int i = 1; i < [ablum.ablum_categorys count]; i++) {
            AblumCategory * category = [ablum.ablum_categorys objectAtIndex:i];
            NSMutableString *url = [NSMutableString stringWithFormat:AblumURL, _image_SS, _image_SP, 0];
            [url replaceOccurrencesOfString:@"t0" withString:[NSString stringWithFormat:@"t%d", [category.ablum_id intValue]] options:NSCaseInsensitiveSearch range:NSMakeRange(0, [url length])];
            [NetUrl connect:url parmater:nil Block:^(NSData *data) {
                NSDictionary *dictionary = (NSDictionary *)data;
                NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
                AblumModel *ablum = [AblumModel returnAblumModel:dic];
                [_ablumArray addObjectsFromArray:ablum.ablum_list];
                [self createScrollContentSize];
            }];
        }
        [self createScrollContentSize];
    }];
}

- (void)connectURL_picture:(NSString *)url
{
    [NetUrl connect:url parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableArray *array = [[dictionary objectForKey:@"result"] objectForKey:@"piclist"];
    
        for (NSMutableDictionary *dic in array) {
            
            NSMutableString *picture_url = [NSMutableString stringWithFormat:@"%@", [dic objectForKey:@"smallpic"]];
            
//            NSRange range = [picture_url rangeOfString:@"s_"];//删除字符串中得字符there
//            //range.length++;
//            [picture_url deleteCharactersInRange:range];
        
            [picture_url replaceOccurrencesOfString:@"s_" withString:@"k_"options:NSCaseInsensitiveSearch range:NSMakeRange(0, [picture_url length])];
            
            [_ablumArray addObject:picture_url];
        }
        [self createScrollContentSize_picture];
    }];
}

#pragma mark -
#pragma mark createUpView
- (void)createUpView
{
    _up_View = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 50)];
    _up_View.backgroundColor = myColor_dark;
    [self.view addSubview:_up_View];
    [_up_View release];
    //返回button
    UIButton *up_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [up_backButton setFrame:CGRectMake(0, 5, 50, 40)];
//    [up_backButton setBackgroundColor:[UIColor whiteColor]];
//    [up_backButton setTitle:@"返回" forState:UIControlStateNormal];
    
    [up_backButton setImage:[UIImage imageNamed:@"BackButton.png"] forState:UIControlStateNormal];
    
    [up_backButton addTarget:self action:@selector(backToChannelVC:) forControlEvents:UIControlEventTouchUpInside];
    [_up_View addSubview:up_backButton];
    //显示图片张数
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 5, 90, 40)];
    _titleLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.layer.cornerRadius = 10.0;
    _titleLabel.font = [UIFont boldSystemFontOfSize:20];
    _titleLabel.clipsToBounds = YES;
    _titleLabel.text = [NSString stringWithFormat:@"%d/%d", 1, (int)[_ablumArray count]];
    [_up_View addSubview:_titleLabel];
    [_titleLabel release];
    
}
#pragma mark createDownView
- (void)createDownView
{
    _down_View = [[UIView alloc] initWithFrame:CGRectMake(0, 528, self.view.frame.size.width, 40)];
    _down_View.backgroundColor = myColor_dark;
    [self.view addSubview:_down_View];
    [_down_View release];
    
    int tag = 10;
    for (int i = 0; i < [_ablumCategory count]; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake((self.view.frame.size.width / 5.0) * i, 0, self.view.frame.size.width / 5.0, _down_View.frame.size.height)];
        [button setBackgroundColor:[UIColor whiteColor]];
        AblumCategory *ablumCat = [_ablumCategory objectAtIndex:i];
        [button setTitle:ablumCat.ablum_name forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.tag = tag;
        tag++;
        [button addTarget:self action:@selector(changePic:) forControlEvents:UIControlEventTouchUpInside];
        [_down_View addSubview:button];
    }
}
#pragma mark 滚动相册
- (void)createScrollAblum
{
    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2 - 120, self.view.frame.size.width, 240)];
    _scroll.pagingEnabled = YES;
    _scroll.backgroundColor = [UIColor grayColor];
    _scroll.bounces = NO;
    _scroll.delegate = self;
    _scroll.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_scroll];
    [_scroll release];
}
#pragma mark 设置胶片和滚动范围
- (void)createScrollContentSize
{
    for (int i = 0; i < [_ablumArray count]; i++) {
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _scroll.frame.size.width, _scroll.frame.size.height)];
        AblumList *list = [_ablumArray objectAtIndex:i];
        [image sd_setImageWithURL:[NSURL URLWithString:list.ablum_imgUrl] placeholderImage:[UIImage imageNamed:@"Loading.png"]];

        UIScrollView *little = [[UIScrollView alloc] initWithFrame: CGRectMake(_scroll.frame.size.width * i, 0, _scroll.frame.size.width, _scroll.frame.size.height)];
        little.delegate = self;
        little.minimumZoomScale = 0.5;
        little.maximumZoomScale = 2.0;
        little.showsHorizontalScrollIndicator = NO;
        little.showsVerticalScrollIndicator = NO;
        [little addSubview:image];
        [_scroll addSubview:little];
        [image release];
        [little release];

        _scroll.contentSize = CGSizeMake(_scroll.frame.size.width * (i + 1), 0);
    }
    _titleLabel.text = [NSString stringWithFormat:@"%d/%d", 1, (int)[_ablumArray count]];
}

#pragma mark 设置胶片和滚动范围 -- 图片
- (void)createScrollContentSize_picture
{
    for (int i = 0; i < [_ablumArray count]; i++) {
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _scroll.frame.size.width, _scroll.frame.size.height)];
        NSString *str = [NSString stringWithFormat:@"%@", [_ablumArray objectAtIndex:i]];
        [image sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"Loading.png"]];
        
        UIScrollView *little = [[UIScrollView alloc] initWithFrame: CGRectMake(_scroll.frame.size.width * i, 0, _scroll.frame.size.width, _scroll.frame.size.height)];
        little.delegate = self;
        little.minimumZoomScale = 0.5;
        little.maximumZoomScale = 2.0;
        little.showsHorizontalScrollIndicator = NO;
        little.showsVerticalScrollIndicator = NO;
        [little addSubview:image];
        [_scroll addSubview:little];
        [image release];
        [little release];
        
        _scroll.contentSize = CGSizeMake(_scroll.frame.size.width * (i + 1), 0);
    }
    _titleLabel.text = [NSString stringWithFormat:@"%d/%d", 1, (int)[_ablumArray count]];
}

#pragma mark -
#pragma mark ScrollViewDelegate
///  缩放
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    NSArray *array = [scrollView subviews]; // 获得所有子视图
    UIImageView *myImage = [array objectAtIndex:0];
    return myImage;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (_scroll == scrollView) {
        NSArray *scroll = [_scroll subviews];
        for (UIScrollView *scrolls in scroll) {
            if ([scrolls isKindOfClass:[UIScrollView class]]) {
                scrolls.zoomScale = 1.0;
            }
        }
    }
    _titleLabel.text = [NSString stringWithFormat:@"%.0f/%d", _scroll.contentOffset.x / 320 + 1, (int)[_ablumArray count]];
}
#pragma mark -
#pragma mark 返回按钮点击函数
- (void)backToChannelVC:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark 底部button的点击函数
- (void)changePic:(id)sender
{
    UIButton *button = (UIButton *)sender;
    AblumCategory *ablum = [_ablumCategory objectAtIndex:button.tag - 10];
    _scroll.contentOffset = CGPointMake([ablum.ablum_picCount intValue] * self.view.frame.size.width, 0);
}

#pragma mark -
#pragma mark ablum的方法传值
- (void)setWithIndexDetail:(NSString *)indexDetail ID:(int)imageID
{
    _imageID = imageID;
    //将字符串以㊣分隔开,存成数组
    NSArray *array = [indexDetail componentsSeparatedByString:@"㊣"];
    _image_SS = [[array firstObject] intValue];
    _image_SP = [[array objectAtIndex:1] intValue];
    //开始网络请求
    [self connectURL];

}
#pragma mark -
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
